package com.chatroom.service.impl;

import com.chatroom.model.PrivateChatRoom;
import com.chatroom.model.User;
import com.chatroom.repository.PrivateChatRoomRepository;
import com.chatroom.service.PrivateChatRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

@Service
public class PrivateChatRoomServiceImpl implements PrivateChatRoomService {

    private static final Logger logger = LoggerFactory.getLogger(PrivateChatRoomServiceImpl.class);
    private final PrivateChatRoomRepository privateChatRoomRepository;
    
    @Autowired
    public PrivateChatRoomServiceImpl(PrivateChatRoomRepository privateChatRoomRepository) {
        this.privateChatRoomRepository = privateChatRoomRepository;
    }
    
    @Override
    public PrivateChatRoom getOrCreatePrivateChatRoom(User user1, User user2) {
        // 先尝试查找现有的房间
        Optional<PrivateChatRoom> existingRoom = findByUsers(user1, user2);
        
        if (existingRoom.isPresent()) {
            logger.info("找到现有私聊房间: {}", existingRoom.get().getRoomCode());
            return existingRoom.get();
        }
        
        // 创建新的私聊房间
        String roomCode = PrivateChatRoom.generateRoomCode(user1, user2);
        PrivateChatRoom newRoom = new PrivateChatRoom();
        newRoom.setRoomCode(roomCode);
        newRoom.setUser1(user1);
        newRoom.setUser2(user2);
        
        privateChatRoomRepository.save(newRoom);
        logger.info("创建新的私聊房间: {}", roomCode);
        
        return newRoom;
    }
    
    @Override
    public Optional<PrivateChatRoom> findByRoomCode(String roomCode) {
        return privateChatRoomRepository.findByRoomCode(roomCode);
    }
    
    @Override
    public Optional<PrivateChatRoom> findByUsers(User user1, User user2) {
        return privateChatRoomRepository.findByUsers(user1, user2);
    }
} 